package com.zhiyizhen.handheld.component.pharmacy;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zhiyizhen.handheld.R;
import com.zhiyizhen.handheld.common.DataCache;
import com.zhiyizhen.handheld.common.ImageLoader;
import com.zhiyizhen.handheld.common.LogUtil;
import com.zhiyizhen.handheld.common.RxJavaUtil;
import com.zhiyizhen.handheld.common.StringUtil;
import com.zhiyizhen.handheld.common.ToastUtil;
import com.zhiyizhen.handheld.common.event.AddRegimenRecordEvent;
import com.zhiyizhen.handheld.common.event.PharmacyStatusEvent;
import com.zhiyizhen.handheld.common.view.BaseFragment;
import com.zhiyizhen.handheld.common.view.CommonDialog;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.component.main.bean.EnumsBean;
import com.zhiyizhen.handheld.component.pharmacy.adapter.RegimenDetailAdapter;
import com.zhiyizhen.handheld.component.pharmacy.api.IRegimenDosageService;
import com.zhiyizhen.handheld.component.pharmacy.bean.CompleteRegimenReq;
import com.zhiyizhen.handheld.component.pharmacy.bean.GroupDetailListBean;
import com.zhiyizhen.handheld.component.pharmacy.bean.GroupListBean;
import com.zhiyizhen.handheld.component.pharmacy.bean.RegimenDetailBean;
import com.zhiyizhen.handheld.component.pharmacy.bean.RxListBean;
import com.zhiyizhen.handheld.databinding.FragmentRegimenDosageDetailBinding;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class RegimenDosageDetailFragment extends BaseFragment {
    private FragmentRegimenDosageDetailBinding binding;
    private LoginBean loginBean;

    private String orderId;
    private EnumsBean enumsBean;
    private RecyclerView mRecyclerView;
    private RegimenDetailAdapter regimenDetailAdapter;
    private List<RxListBean> rxList;

    public void setExtraData(EnumsBean enumsBean, String orderId) {
        this.orderId = orderId;
        this.enumsBean = enumsBean;
        getDetail(orderId);
        binding.contentLayout.setVisibility(View.VISIBLE);
        binding.emptyView.setVisibility(View.GONE);
    }

    public void setEmptyData() {
        binding.contentLayout.setVisibility(View.GONE);
        binding.emptyView.setVisibility(View.VISIBLE);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentRegimenDosageDetailBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loginBean = DataCache.getLoginBean();
        initView();
    }

    private void initView() {
        // 等视图加载完成后获取父容器尺寸
        binding.parentLayout.post(() -> {
            if (binding.parentLayout.getParent() instanceof View) {
                View parentView = (View) binding.parentLayout.getParent();
                // 等待父容器完成测量
                parentView.post(() -> {
                    // 设置固定尺寸
                    ViewGroup.LayoutParams params = binding.parentLayout.getLayoutParams();
                    params.width = LinearLayout.LayoutParams.MATCH_PARENT;
                    params.height = LinearLayout.LayoutParams.MATCH_PARENT;
                    binding.parentLayout.setLayoutParams(params);
                });
            }
            binding.contentLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        });

        mRecyclerView = binding.recyclerView;
        regimenDetailAdapter = new RegimenDetailAdapter(getContext());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        binding.regimenDosageBtn.setOnClickListener(v -> showRegimenDialog());

    }

    private CommonDialog dialog;

    public void showRegimenDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_regimen_dosage, (ViewGroup) getActivity().getWindow().getDecorView(), false);

        CommonDialog.Builder builder = new CommonDialog.Builder(getActivity());
        builder.setView(view);

        builder.setCancelable(false);
        dialog = builder.show();

        view.findViewById(R.id.cancel_button).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.okBtn).setOnClickListener(v -> regimen());
    }

    private void setData(RegimenDetailBean data) {
        if ("1".equals(data.getPatientGender())) {
            ImageLoader.load(getContext(), R.drawable.icon_man, binding.genderImg);
        } else if ("2".equals(data.getPatientGender())) {
            ImageLoader.load(getContext(), R.drawable.icon_woman, binding.genderImg);
        } else {
            ImageLoader.load(getContext(), R.drawable.icon_unknow, binding.genderImg);
        }
        binding.genderTv.setText(StringUtil.getGender(data.getPatientGender(), enumsBean));

        binding.userNameTv.setText(data.getPatientName());
        binding.doctorNameTv.setText(data.getDoctorName());
        binding.ageTv.setText(StringUtil.getAge(data.getAgeYear(), data.getAgeMonth()));
        if (data.getWeight() != null) {
            binding.weightTv.setText(data.getWeight() + "kg");
            binding.divideLeftOfWeight.setVisibility(View.VISIBLE);
        } else {
            binding.weightTv.setText(null);
            binding.divideLeftOfWeight.setVisibility(View.GONE);
        }

        if (data.getSystolicBp() != null && data.getDiastolicBp() != null) {
            binding.bloodPressureTv.setText(data.getSystolicBp() + "/" + data.getDiastolicBp() + " mmHg");
            binding.divideLeftOfBlood.setVisibility(View.VISIBLE);
        } else {
            binding.bloodPressureTv.setText(null);
            binding.divideLeftOfBlood.setVisibility(View.GONE);
        }
        binding.phoneTv.setText(data.getPatientPhone());
        binding.deptNameTv.setText(data.getDeptName());
        binding.deptNameTv.setText(data.getDeptName());
        binding.diagnosisTv.setText(data.getDiagnosis());
        binding.diagnosisTimeTv.setText(data.getDiagnosisTime());

        rxList = data.getRxList();
        regimenDetailAdapter.setDatas(data.getRxList());
        mRecyclerView.setAdapter(regimenDetailAdapter);

        if ("3".equals(data.getDispenseStatus()) || "2".equals(data.getDispenseStatus())) {
            binding.regimenDosageBtn.setVisibility(View.GONE);
        } else {
            binding.regimenDosageBtn.setVisibility(View.VISIBLE);
        }
    }

    private void getDetail(String orderId) {
        ServiceFactory.getService(IRegimenDosageService.class)
                .getDispenseDetail(loginBean.getToken(), loginBean.getClinicId(), orderId)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<RegimenDetailBean> responseData) {
                        if (responseData != null && responseData.getData() != null) {
                            setData(responseData.getData());
                        }
                    }
                });
    }

    private void regimen() {
        boolean allRegimen = true;
        CompleteRegimenReq rejectDeliveryReq = new CompleteRegimenReq();
        rejectDeliveryReq.setOrderId(orderId);
        if (rxList == null || rxList.isEmpty()) {
            return;
        }
        List<CompleteRegimenReq.RxListBeanReq> rxListBeanReqList = new ArrayList<>();
        RxListBean rxListBean;
        for (int i = 0; i < rxList.size(); i++) {
            rxListBean = rxList.get(i);
            LogUtil.d("allRegimen == 1");
            // 成药
            if (TextUtils.equals(rxListBean.getRxType(), "1")) {
                LogUtil.d("allRegimen == 2");
                if (TextUtils.equals(rxListBean.getDispenseStatus(), "1")) {
                    LogUtil.d("allRegimen == 3");
                    CompleteRegimenReq.RxListBeanReq rxListBeanReq1 = getRxListBeanReq(rxListBean);
                    rxListBeanReqList.add(rxListBeanReq1);
                } else if (TextUtils.equals(rxListBean.getDispenseStatus(), "0")) {
                    LogUtil.d("allRegimen == 4-false");
                    allRegimen = false;
                }
            } else if (TextUtils.equals(rxListBean.getRxType(), "2")) {
                LogUtil.d("allRegimen == 5");
                // 输液
                CompleteRegimenReq.RxListBeanReq rxListBeanReq2 = new CompleteRegimenReq.RxListBeanReq();
                rxListBeanReq2.setRxId(rxListBean.getRxId());
                rxListBeanReq2.setRxType(rxListBean.getRxType());
                List<CompleteRegimenReq.GroupListReq> groupList = new ArrayList<>();
                CompleteRegimenReq.GroupListReq groupListReq;
                for (int j = 0; j < rxListBean.getGroupList().size(); j++) {
                    LogUtil.d("allRegimen == 6");

                    if (TextUtils.equals(rxListBean.getGroupList().get(j).getDispenseStatus(), "1")) {
                        LogUtil.d("allRegimen == 7");
                        groupListReq = new CompleteRegimenReq.GroupListReq();
                        groupListReq.setGroupName(rxListBean.getGroupList().get(j).getGroupName());
                        List<CompleteRegimenReq.GroupDetailListReq> detailList = getGroupDetailListReqs(rxListBean, j);
                        groupListReq.setDetailList(detailList);
                        groupList.add(groupListReq);
                    } else if (TextUtils.equals(rxListBean.getGroupList().get(j).getDispenseStatus(), "0")) {
                        LogUtil.d("allRegimen == 8-false");
                        allRegimen = false;
                    }

                    List<GroupDetailListBean> groupDetailListBean = rxListBean.getGroupList().get(j).getDetailList();
                    for (int k = 0; k < groupDetailListBean.size(); k++) {
                        int total = groupDetailListBean.get(k).getTotalOutQty();
                        int hasGive = groupDetailListBean.get(k).getDispenseQty();
                        int current = Integer.parseInt(groupDetailListBean.get(k).getCurrentDispenseQty());
                        LogUtil.d(total + ";" + hasGive + ";" + current);
                        if (total - hasGive - current > 0) {
                            allRegimen = false;
                        }
                    }
                }
                if (!groupList.isEmpty()) {
                    LogUtil.d("allRegimen == 9");
                    rxListBeanReq2.setGroupList(groupList);
                    rxListBeanReqList.add(rxListBeanReq2);
                }
            } else {
                LogUtil.d("allRegimen == 10");
                // 中药配方
                if (TextUtils.equals(rxListBean.getDispenseStatus(), "1")) {
                    LogUtil.d("allRegimen == 11");
                    CompleteRegimenReq.RxListBeanReq rxListBeanReq3 = getRxListBeanReq3(rxListBean);
                    rxListBeanReqList.add(rxListBeanReq3);
                } else if (TextUtils.equals(rxListBean.getDispenseStatus(), "0")) {
                    LogUtil.d("allRegimen == 12-false");
                    allRegimen = false;
                }
            }

            rejectDeliveryReq.setRxList(rxListBeanReqList);
        }

        LogUtil.d("allRegimen == " + allRegimen);
        boolean finalAllRegimen = allRegimen;
        ServiceFactory.getService(IRegimenDosageService.class)
                .completeDispense(loginBean.getToken(), loginBean.getClinicId(), rejectDeliveryReq)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        ToastUtil.showShort("操作成功");
                        EventBus.getDefault().post(new AddRegimenRecordEvent());
                        dialog.dismiss();

                        binding.regimenDosageBtn.setVisibility(View.GONE);
                        if (finalAllRegimen) {
                            EventBus.getDefault().post(new PharmacyStatusEvent(PharmacyStatusEvent.TYPE_REGIMEN, orderId, "3"));
                        }
                        getDetail(orderId);
                    }
                });
    }

    private static CompleteRegimenReq.RxListBeanReq getRxListBeanReq3(RxListBean rxListBean) {
        CompleteRegimenReq.RxListBeanReq rxListBeanReq3 = new CompleteRegimenReq.RxListBeanReq();
        rxListBeanReq3.setRxType(rxListBean.getRxType());
        rxListBeanReq3.setRxId(rxListBean.getRxId());
        CompleteRegimenReq.TcmInfoReq tcmInfoReq = new CompleteRegimenReq.TcmInfoReq();
        tcmInfoReq.setCurrentDispenseQty(rxListBean.getTcmInfo().getTotalDoses() - rxListBean.getTcmInfo().getDispenseQty());
        rxListBeanReq3.setTcmInfo(tcmInfoReq);
        return rxListBeanReq3;
    }

    private static List<CompleteRegimenReq.GroupDetailListReq> getGroupDetailListReqs(RxListBean rxListBean, int j) {
        List<CompleteRegimenReq.GroupDetailListReq> detailList = new ArrayList<>();
        List<GroupDetailListBean> groupDetailListBean = rxListBean.getGroupList().get(j).getDetailList();
        for (int k = 0; k < groupDetailListBean.size(); k++) {
            CompleteRegimenReq.GroupDetailListReq groupDetailListReq = new CompleteRegimenReq.GroupDetailListReq();
            groupDetailListReq.setDrugId(groupDetailListBean.get(k).getDrugId());
            groupDetailListReq.setCurrentDispenseQty(groupDetailListBean.get(k).getCurrentDispenseQty());
            detailList.add(groupDetailListReq);
        }
        return detailList;
    }

    private static CompleteRegimenReq.RxListBeanReq getRxListBeanReq(RxListBean rxListBean) {
        CompleteRegimenReq.RxListBeanReq rxListBeanReq1 = new CompleteRegimenReq.RxListBeanReq();
        rxListBeanReq1.setRxId(rxListBean.getRxId());
        rxListBeanReq1.setRxType(rxListBean.getRxType());
        List<CompleteRegimenReq.DetailListReq> detailList = new ArrayList<>();
        CompleteRegimenReq.DetailListReq detailListReq;
        for (int j = 0; j < rxListBean.getDetailList().size(); j++) {
            detailListReq = new CompleteRegimenReq.DetailListReq();
            detailListReq.setDrugId(rxListBean.getDetailList().get(j).getDrugId());
            detailListReq.setCurrentDispenseQty(rxListBean.getDetailList().get(j).getTotalOutQty() - rxListBean.getDetailList().get(j).getDispenseQty());
            detailList.add(detailListReq);
        }
        rxListBeanReq1.setDetailList(detailList);
        return rxListBeanReq1;
    }

}
